﻿using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using AppFramework.DinosaursParkMes.BOM;
using AppFramework.DinosaursParkMes.BOM.Dto;
using AppFramework.DinosaursParkMes.CodingRuleModel;
using AppFramework.DinosaursParkMes.DomainService.CodingRule;
using AppFramework.DinosaursParkMes.Material.Dto;
using AppFramework.DinosaursParkMes.Process;
using AppFramework.DinosaursParkMes.Production.DTO;
using AppFramework.DinosaursParkMes.ProductWork.Dto;
using AppFramework.DinosaursParkMes.TicketTask;
using AppFramework.DinosaursParkMes.TicketTask.DTO;
using AppFramework.DinosaursParkMes.WorkOrder.Dto;
using AppFramework.Dto;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Org.BouncyCastle.Math.EC.Rfc7748;
using PayPalCheckoutSdk.Orders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AppFramework.DinosaursParkMes.ProductWork
{
    public class ProductWorkAppService : AppFrameworkAppServiceBase, IProductAppService
    {

        private readonly IRepository<ProductWorkModels> _repository;
        private readonly IRepository<BillOfMaterial> _billof;
        private readonly IRepository<AppFramework.DinosaursParkMes.MaterialModel.Material> _mterial;
        private readonly IRepository<BillOfMaterialDetails> _materialdetails;
        private readonly IRepository<CraftRouteModel> _CraftRouteModel;
        private readonly IRepository<CraftProcessModel> _CraftProcessModel;
        private readonly IRepository<TicketTaskinfo> _TicketTaskinfo;
        private readonly ICodingruleManager _codingruleManager;
        private readonly IRepository<AppFramework.DinosaursParkMes.ProductionPlanningModel.ProductionPlanning> _ProductionPlanning;
        public ProductWorkAppService(IRepository<ProductWorkModels> repository, IRepository<BillOfMaterial> billof, IRepository<MaterialModel.Material> mterial, IRepository<BillOfMaterialDetails> materialdetails, IRepository<CraftRouteModel> craftRouteModel, IRepository<CraftProcessModel> craftProcessModel, IRepository<TicketTaskinfo> ticketTaskinfo, ICodingruleManager codingruleManager, IRepository<ProductionPlanningModel.ProductionPlanning> productionPlanning)
        {
            _repository = repository;
            _billof = billof;
            _mterial = mterial;
            _materialdetails = materialdetails;
            _CraftRouteModel = craftRouteModel;
            _CraftProcessModel = craftProcessModel;
            _TicketTaskinfo = ticketTaskinfo;
            _codingruleManager = codingruleManager;
            _ProductionPlanning = productionPlanning;
        }



        //物料清单
        public async Task<List<MateDto>> GetMaterialParticulars()
        {
            var list = from x in _materialdetails.GetAll()
                       join y in _mterial.GetAll() on x.Materialnumber equals y.Materialnumber
                       select new MateDto
                       {
                           Id=x.Id,
                           Usageamount=x.Usageamount,
                           Useratio=x.Useratio,
                           Materialnumber=y.Materialnumber,
                           Name=y.Name,
                           Unit = y.Unit,
                           Specificationsversion = y.Specificationsversion
                       };

            return await list.ToListAsync();
        }
        /// <summary>
        /// 查询的重写
        /// </summary>
        /// <param name="input">查询的信息</param>
        /// <returns></returns>
        //protected override IQueryable<ProductWorkModels> CreateFilteredQuery(ProductInsertDto input)
        //{
        //    return base.CreateFilteredQuery(input)
        //          .Where(t => string.IsNullOrEmpty(input.RWNumberOrName) || (t.WorkOrderNumber.Equals(input.RWNumberOrName) || t.WorkOrderName.Equals(input.RWNumberOrName)))
        //          .Where(t => string.IsNullOrEmpty(input.JHNumberOrName) || (t.ProductNumber.Equals(input.JHNumberOrName) || t.RelevanceExplain.Equals(input.JHNumberOrName)))
        //          .Where(t => string.IsNullOrEmpty(input.ProductName) || t.ProductName.Equals(input.ProductName))
        //          .Where(t => input.State == ProductState.AllOrder || t.State.Equals(input.State))
        //          判断计划开始时间的范围查询
        //          .Where(t => default(DateTime) == input.StartTime || t.ExplainStartDate > input.StartTime)
        //          .Where(t => default(DateTime) == input.StartTime || t.ExplainStartDate < input.StartendTime.AddDays(1))
        //          判断计划结束时间的范围查询
        //          .Where(t => default(DateTime) == input.EndendTime || t.ExplainEndDate > input.EndstartTime)
        //          .Where(t => default(DateTime) == input.EndendTime || t.ExplainEndDate < input.EndendTime.AddDays(1))
        //          判断实际开始时间的范围查询
        //          .Where(t => default(DateTime) == input.ActuallyStartTime || t.PracticalStartDate > input.ActuallyStartTime)
        //          .Where(t => default(DateTime) == input.ActuallyStartTime || t.PracticalStartDate < input.ActuallyStartendTime.AddDays(1))
        //          判断实际完工时间的范围查询
        //          .Where(t => default(DateTime) == input.ActuallyEndTime || t.PracticalEndDate > input.ActuallyEndTime)
        //          .Where(t => default(DateTime) == input.ActuallyEndTime || t.PracticalEndDate < input.ActuallyEndTime.AddDays(1))
        //          需求时间范围查询
        //          .Where(t => default(DateTime) == input.Demandstarttime || t.DemandDate > input.Demandstarttime)
        //          .Where(t => default(DateTime) == input.Demandendtime || t.DemandDate < input.Demandendtime.AddDays(1))
        //          ;
        //}

        /// <summary>
        /// 生产工单列表
        /// </summary>
        public async Task<PagedResultDto<ProductWorkDto>> GetPRoduct(int pagesize, int pageindex, ProductWorkDto dto)
        {
            var list = _repository.GetAll();
            var list1 = list.OrderByDescending(x => x.Id).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
            var list2 = ObjectMapper.Map<List<ProductWorkDto>>(list1);
            var count = list.Count();
            //查询工单名称
            if (!string.IsNullOrEmpty(dto.WorkOrderName))
            {
                list2 = list2.Where(x => x.WorkOrderName.Contains(dto.WorkOrderName)).ToList();
            }
            //查询关联计划名称
            if (!string.IsNullOrEmpty(dto.RelevanceExplain))
            {
                list2 = list2.Where(x => x.RelevanceExplain.Contains(dto.RelevanceExplain)).ToList();
            }
            //查询产品名称
            if (!string.IsNullOrEmpty(dto.ProductName))
            {
                list2 = list2.Where(x => x.WorkOrderName.Contains(dto.ProductName)).ToList();
            }
            return new PagedResultDto<ProductWorkDto>
            {
                TotalCount = count,
                Items = list2
            };
        }

        //查询第一道工序
        public async Task<List<TicketInsertDto>> GetFirst()
        {
            var task = _repository.GetAll().FirstOrDefault();
            var list = await _TicketTaskinfo.GetAll().Where(x => x.Processname == "工序一").ToListAsync();
            return ObjectMapper.Map<List<TicketInsertDto>>(list);
        }
        //查询第二道工序
        public async Task<List<TicketInsertDto>> GetTwo()
        {
            var task = _repository.GetAll().FirstOrDefault();
            var list = await _TicketTaskinfo.GetAll().Where(x => x.Processname == "工序二").ToListAsync();
            return ObjectMapper.Map<List<TicketInsertDto>>(list);
        }
        //查询第三道工序
        public async Task<List<TicketInsertDto>> GetThree()
        {
            var task = _repository.GetAll().FirstOrDefault();
            var list = await _TicketTaskinfo.GetAll().Where(x => x.Processname == "工序三").ToListAsync();
            return ObjectMapper.Map<List<TicketInsertDto>>(list);
        }
        //查询第四道工序
        public async Task<List<TicketInsertDto>> GetFour()
        {
            var task = _repository.GetAll().FirstOrDefault();
            var list = await _TicketTaskinfo.GetAll().Where(x => x.Processname == "工序四").ToListAsync();
            return ObjectMapper.Map<List<TicketInsertDto>>(list);
        }

        /// <summary>
        /// 任务列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<TicketTaskinfoResponseDTO>> GetTick()
        {
            var list = _TicketTaskinfo.GetAll();
            return ObjectMapper.Map<List<TicketTaskinfoResponseDTO>>(list).ToList();
        }

        /// <summary>
        /// 工单计划添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> PlanInsert(TicketInsertDto model)
        {
            var dto= ObjectMapper.Map<TicketTaskinfo>(model);
            var zdname = "zhandian";
            var taskname = "TicketTaskinfo";
            dto.Missionnumber = await _codingruleManager.GetCode(taskname);
            dto.Stationnumber = await _codingruleManager.GetCode(zdname);
            await _TicketTaskinfo.InsertAsync(dto);
            return 1;
        }

        /// <summary>
        /// 生产排产反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("ProductFind")]
        public FindProduct ProductFind(int id)
        {
            FindProduct findProduct = new FindProduct();
            ProductBillOfMaterialDto productBillOfMaterialDto = new ProductBillOfMaterialDto();
            var list = _repository.GetAllList().Where(x => x.Id == id).FirstOrDefault();
            findProduct = ObjectMapper.Map<FindProduct>(list);
            //查找bom
            var plan= _ProductionPlanning.FirstOrDefault(x => x.Planningnumber==list.ExplainNumber);
            var bom2= _billof.FirstOrDefault(x => x.Numberbom == plan.BOMNumber);
            findProduct.BOMV = bom2.Versionnumber;
            findProduct.BOMNumber = bom2.Numberbom;
            var process = _CraftProcessModel.FirstOrDefault(x => x.Craftcode == bom2.Processnumber);
            var process2 = _CraftRouteModel.FirstOrDefault(x => x.Routecoded == bom2.Processnumber);
            findProduct.RoutingNumber = process.Craftcode;
            findProduct.RoutingName= process2.Routename;
            //查询物料表数据
            //var matel = _mterial.GetAll().FirstOrDefault();
            //查找物料清单
            //List<BillOfMaterialDetails> mate = _materialdetails.GetAll().Where(x => x.Numberbom == Bom.Numberbom && x.Materialnumber == matel.Materialnumber).ToList();
            //var mate2 = ObjectMapper.Map<List<ProductBillOfMaterialDto>>(mate);
            //foreach (var item in mate2)
            //{
            //    item.MaterialName = matel.Name;
            //    item.Unit = matel.Unit;
            //}
            //findProduct.BillOfMaterials = mate2;
            //查找工序
            //List<CraftRouteModel> listprocess = _CraftRouteModel.GetAll().Where(x => x.Routecoded == Bom.Processnumber).ToList();
            //findProduct.ProcessInfos = ObjectMapper.Map<List<PRoductProcessInfoDto>>(listprocess);
            //物料清单

            var list1 = from x in _materialdetails.GetAll()
                       join y in _mterial.GetAll() on x.Materialnumber equals y.Materialnumber
                       select new ProductBillOfMaterialDto
                       {
                           Id = x.Id,
                           Usageamount = x.Usageamount,
                           Useratio = x.Useratio,
                           Materialnumber = y.Materialnumber,
                           Name = y.Name,
                           Unit = y.Unit,
                           Specificationsversion = y.Specificationsversion
                       };
            findProduct.BillOfMaterials = ObjectMapper.Map<List<ProductBillOfMaterialDto>>(list1);
            return findProduct;
        }
      
    }
}
